<template>
  <div>
    <!-- 面包屑导航区域 -->
    <bread-crumb :breadContent="breadContent"></bread-crumb>

    <!-- 卡片视图 -->
    <el-card>
      <!-- 搜索与添加区域 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <!-- <el-input placeholder="请输入内容" v-model="queryInfo.key" clearable @clear="getuserList">
            <el-button slot="append" icon="el-icon-search" @click="getuserList"></el-button>
          </el-input>-->
        </el-col>
        <el-col :span="4">
          <el-button type="primary"
                     @click="showAddEditDialog">添加角色</el-button>
        </el-col>
      </el-row>
      <br />

      <el-table :data="roleList"
                border
                stripe>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称"
                         prop="name"></el-table-column>
        <el-table-column label="角色描述"
                         prop="description"></el-table-column>
        <el-table-column label="操作"
                         width="227px"
                         align="center">
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-button type="primary"
                       icon="el-icon-edit"
                       size="mini"
                       @click="showEditDialog(scope.row.id)"></el-button>
            <!-- 删除按钮 -->
            <el-button type="danger"
                       icon="el-icon-delete"
                       size="mini"
                       @click="removeRoleById(scope.row.id)"></el-button>
            <!-- 分配角色按钮 -->
            <el-tooltip effect="dark"
                        content="分配权限"
                        placement="top"
                        :enterable="false">
              <el-button type="warning"
                         icon="el-icon-setting"
                         size="mini"
                         @click="setPermission(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加或修改用户的对话框 -->
    <el-dialog :title="dialogName"
               :visible.sync="addDialogVisible"
               width="50%"
               @close="addDialogClosed">
      <!-- 内容主体区域 -->
      <el-form :model="addForm"
               ref="addFormRef"
               label-width="70px">
        <el-form-item label="角色名称"
                      prop="name">
          <el-input v-model="addForm.name"></el-input>
        </el-form-item>
        <el-form-item label="角色描述"
                      prop="description">
          <el-input v-model="addForm.description"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="addRole">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色的对话框 -->
    <el-dialog title="分配角色所绑定权限"
               :visible.sync="rolePermissionDialogVisible"
               width="50%"
               @close="setPermissionDialogClosed">
      <el-tree :data="permissionList"
               :props="defaultProps"
               @node-click="handleNodeClick"
               @check-change="handleCheckChange"
               show-checkbox
               check-on-click-node
               node-key="id"
               ref="DeviceGroupTree"
               :default-expanded-keys="permissionIds"
               :default-checked-keys="permissionIds">
      </el-tree>

      <span slot="footer"
            class="dialog-footer">
        <el-button @click="rolePermissionDialogVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="updateRolePermissions">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  inject: ['reload'],
  data () {
    return {
      breadContent: ["权限管理", "角色列表"],
      roleList: [],
      menuList: [],
      rolePermissionDialogVisible: false,
      parentPermissions: [],
      roleInfo: {},
      addDialogVisible: false,
      addForm: {
        id: '',
        name: '',
        description: ''
      },
      dialogName: '',
      // 权限列表
      permissionList: [],
      // 复选框相关
      checkAll: false,
      checkedPermissions: [],
      isIndeterminate: true,
      permissionIds: [],  // 选中的权限id
      defaultProps: {
        children: 'children',
        label: 'name'
      },
    }
  },
  created () {
    // 获取所有的角色
    this.listRoles()
    // this.listAllPermission()
    // 获取权限列表
    this.getPermissionList()
  },
  methods: {
    // 监听添加角色对话框的关闭事件
    addDialogClosed () {
      this.$refs.addFormRef.resetFields()
    },
    // 展示添加角色的对话框
    showAddEditDialog () {
      this.addDialogVisible = true
      this.dialogName = '添加角色'
      this.addForm.name = ''
      this.addForm.description = ''
      this.addForm.id = undefined
    },
    // 点击按钮，添加新角色
    addRole () {
      this.dialogName = '添加角色'
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        // 可以发起添加角色的网络请求
        const { data: res } = await this.$http.post('role/add', this.addForm)
        if (res.status !== 201) {
          this.$message.error('添加或修改角色失败！')
        }
        this.$message.success('添加或修改角色成功！')
        // 隐藏添加角色的对话框
        this.addDialogVisible = false
        // 重新获取角色列表数据
        this.listRoles()
        this.$refs.addFormRef.resetFields()
      })
    },
    // 根据Id删除对应的角色信息
    async removeRoleById (id) {
      // 弹框询问角色是否删除数据
      const confirmResult = await this.$confirm(
        '此操作将永久删除该角色, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const { data: res } = await this.$http.delete('role/' + id)
      if (res.status !== 200) {
        return this.$message.error('删除角色失败！')
      }
      this.$message.success('删除角色成功！')
      this.listRoles()
    },
    // 展示编辑用户的对话框
    async showEditDialog (id) {
      this.dialogName = '编辑角色信息'
      const { data: res } = await this.$http.get('role/' + id)
      if (res.status !== 200) {
        return this.$message.error('查询角色信息失败！')
      }
      this.addForm = res.data
      this.addDialogVisible = true
    },
    // 监听修改用户对话框的关闭事件
    editDialogClosed () {
      this.$refs.editFormRef.resetFields()
    },

    // 展示分配角色的对话框
    async setPermission (roleInfo) {
      this.permissionIds = []
      this.roleInfo = roleInfo
      // 获取当前角色已经绑定的权限信息
      const { data: res } = await this.$http.get(`permission/list/roleId=${roleInfo.id}`)
      if (res.status !== 200) {
        return this.$message.error('获取权限列表失败！')
      }

      // 将已绑定的权限id信息赋值给 permissionIds
      if (res.data.length !== 0) {
        res.data.forEach(item => {
          this.permissionIds.push(item.id)
        })
      }
      this.rolePermissionDialogVisible = true
    },

    // 监听分配权限对话框的关闭事件
    setPermissionDialogClosed () {
      this.roleInfo = {}
      this.permissionIds = []
      this.reload()
    },

    // 为角色分配权限的事件
    async updateRolePermissions () {
      const { data: res } = await this.$http.post('role/bind/permissions', {
        permissionIds: this.permissionIds,
        roleId: this.roleInfo.id
      })
      if (res.status !== 200) {
        return this.$message.error('分配权限失败！')
      }
      this.$message.success('分配权限成功')
      this.setPermissionDialogClosed()
      this.rolePermissionDialogVisible = false
    },

    // 获取角色列表
    async listRoles () {
      const { data: res } = await this.$http.get('role/list')
      if (res.status !== 200) {
        return this.$message.error('获取角色列表失败！')
      }
      console.log(res.data)
      this.roleList = res.data
    },
    // 获取树型权限列表
    async getPermissionList () {
      const { data: res } = await this.$http.get('permission/list/tree')
      if (res.status !== 200) {
        return this.$message.error('获取权限列表失败！')
      }
      this.permissionList = res.data
    },

    // 点击树型控件选项文字
    handleNodeClick (data) {
      // this.permissionIds.forEach(item => {
      //   if(!item.id){
      //     this.permissionIds.push(data.id)
      //   }
      // })
    },

    // 点击树型控件选项选择框
    handleCheckChange (data, checked, indeterminate) {
      // console.log(data, checked, indeterminate);
      this.permissionIds = this.$refs.DeviceGroupTree.getCheckedKeys(true, false)
      // console.log(this.permissionIds)
    },
  }
}
</script>
<style lang="less" scoped>
</style>
